import {
  userLogin,
  logout,
  getUserInfo
} from '@/api/administrator'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    userInfo: null
  },

  mutations: {
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo;
      // console.log("++++++++++",state.userInfo);
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },


  actions: {
    // 登录
    async Login({
      commit
    }, userInfo) {
      let res
      try {
        res = await userLogin(userInfo)
        if (res.code === 1) {
          const tokenStr = res.data.tokenHead + res.data.token
          setToken(tokenStr)
          commit('SET_TOKEN', tokenStr)
        }
        return res
      } catch (error) {
        return Promise.reject(error)
      }

    },

    // 获取用户信息
    GetInfo({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(response => {
          const data = response.data;
          // console.log("=个人信息=======", data);
          commit('SET_USERINFO', data)
          if (data.code == 1) {
            // if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            // commit('SET_ROLES', data.roles)
            // } else {
            //   reject('getUserInfo: roles must be a non-null array !')
            // }
            commit('SET_ROLES', data.roles)
            commit('SET_NAME', data.username)
            commit('SET_AVATAR', data.icon)
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    FedLogOut({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    // FedLogOut({
    //   commit
    // }) {
    //   return new Promise(resolve => {
    //     commit('SET_TOKEN', '')
    //     removeToken()
    //     resolve()
    //   })
    // }
  }
}

export default user
